package xuegao.study.mall.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xuegao.study.mall.web.config.AlipayConfig;
import xuegao.study.mall.web.domain.AlipayParam;
import xuegao.study.mall.web.service.AlipayService;
import xuegao.study.mall.web.service.PortalOrderService;

import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    private Logger logger  = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private PortalOrderService portalOrderService;

    @Override
    public String pay(AlipayParam alipayParam) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        if (StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())) {
            //异步接收地址,公网可访问
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
        }
        if (StrUtil.isNotEmpty(alipayConfig.getReturnUrl())) {
            //同步跳转地址
            request.setReturnUrl(alipayConfig.getReturnUrl());
        }
        /********** 必传参数 **********/
        JSONObject bizContent = new JSONObject();
        // 商户订单号,商家自定义,保持唯一性
        bizContent.put("out_trade_no", alipayParam.getOutTradeNo());
        // 支付金额,最小值0.01元
        bizContent.put("total_amount", alipayParam.getTotalAmount());
        // 订单标题,不可使用特殊符号
        bizContent.put("subject", alipayParam.getSubject());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        String formHtml = null;
        try {
            formHtml = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return formHtml;
    }

    @Override
    public String webPay(AlipayParam alipayParam) {
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        if (StrUtil.isNotEmpty(alipayConfig.getNotifyUrl())) {
            //异步接收地址,公网可访问
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
        }
        if (StrUtil.isNotEmpty(alipayConfig.getReturnUrl())) {
            //同步跳转地址
            request.setReturnUrl(alipayConfig.getReturnUrl());
        }
        /********** 必传参数 **********/
        JSONObject bizContent = new JSONObject();
        // 商户订单号,商家自定义,保持唯一性
        bizContent.put("out_trade_no", alipayParam.getOutTradeNo());
        // 支付金额,最小值0.01元
        bizContent.put("total_amount", alipayParam.getTotalAmount());
        // 订单标题,不可使用特殊符号
        bizContent.put("subject", alipayParam.getSubject());
        bizContent.put("product_code", "QUICK_WAP_WAY");
        request.setBizContent(bizContent.toString());
        String formHtml = null;
        try {
            formHtml = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return formHtml;
    }

    @Override
    public String notify(Map<String, String> params) {
        String result = "failure";
        boolean signVerified = false;
        try {
            AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (AlipayApiException e) {
            logger.error("支付回调签名校验异常!", e);
            e.printStackTrace();
        }
        if (signVerified) {
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                result = "success";
                logger.info("notify方法被调用了,tradeStatus:{}", tradeStatus);
                String outTradeNo = params.get("out_trade_no");
                portalOrderService.paySuccessByOrderSn(outTradeNo, 1);
            } else {
                logger.warn("订单未支付成功,trade_status:{}", tradeStatus);
            }
        } else {
            logger.warn("支付宝回调签名校验失败");
        }
        return result;
    }

    @Override
    public String query(String outTradeNo, String tradeNo) {
        // todo
        return null;
    }
}
